package com.chinaums.xm.wechat.service.wechat;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.chinaums.xm.wechat.WeixinConstant;
import com.chinaums.xm.wechat.domain.wechat.AccessToken;
import com.chinaums.xm.wechat.service.Communicator;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * 通用微信接口
 * @author chenjf
 *
 */
@Service
public class CommonService {

	@Resource
	private Communicator communicator;
	
	/**
	 * 获取access_token
	 * @return
	 */
	public Optional<AccessToken> getAccessToken(){
		final AccessToken accessToken = new AccessToken();
		final String accessTokenUrl = WeixinConstant.ACCESS_TOKEN_URL.replace("APPID", WeixinConstant.APP_ID).replace("APPSECRET", WeixinConstant.APP_SECRET);
		final Optional<String> optionalResponseMsg = communicator.getRequest(accessTokenUrl);
		if(optionalResponseMsg.isPresent()){
			final JSONObject json = JSONObject.fromObject(optionalResponseMsg.get());
			final String token = json.getString("access_token");
			final String expiresIn = json.getString("expires_in");
			accessToken.setToken(token);
			accessToken.setExpiresIn(expiresIn);
			return Optional.of(accessToken);
		} else {
			return Optional.empty();
		}
	}
	
	/**
	 * 获取微信JS接口的临时票据
	 * @return
	 */
    public Optional<String> getJsApiTicket() {
    	final Optional<AccessToken> accessToken = getAccessToken();
    	if(accessToken.isPresent()){
    		String requestUrl = WeixinConstant.JSAPI_TICKET_URL.replace("ACCESS_TOKEN", accessToken.get().getToken());
    		final Optional<String> response = communicator.getRequest(requestUrl);
    		if(response.isPresent()){
    			final JSONObject jsonObject = JSONObject.fromObject(response.get());
    			if(jsonObject != null ){
    				final String ticket = jsonObject.getString("ticket");
    				return Optional.of(ticket);
    			}
    		}
    	}
    	return Optional.empty();
    }
	
	/**
	 * 获取微信服务器IP地址
	 * @return
	 */
	public Optional<List<String>> getServerIpList(){
		final List<String> ipList = new ArrayList<>();
		final String ipListUrl = WeixinConstant.IP_URL.replace("ACCESS_TOKEN", getAccessToken().get().getToken());
		final Optional<String> optionalResponseMsg = communicator.getRequest(ipListUrl);
		if(optionalResponseMsg.isPresent()){
			final JSONObject responsMsg = JSONObject.fromObject(optionalResponseMsg.get());
			final JSONArray ipArr = responsMsg.getJSONArray("ip_list");
			for (int i = 0; i < ipArr.size(); i++) {
				ipList.add(ipArr.getString(i));
			}
			return Optional.of(ipList);
		} else {
			return Optional.empty();
		}
	}
}
